package proxy

import (
	"bytes"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"net"
	"net/http"
	"strings"
)

var (
	config Config
)

func init() {
	data, _ := ioutil.ReadFile("config.yaml")
	yaml.NewDecoder(bytes.NewReader(data)).Decode(&config)
}

type RuleManager struct {
	config Config
}

func (RuleManager) Blocked(r *http.Request) bool {
	var fullURL string
	h, port, _ := net.SplitHostPort(r.URL.Host)
	if port == "80" || port == "443" {
		fullURL = r.URL.Scheme + "://" + h + r.URL.Path
	} else {
		fullURL = r.URL.Scheme + "://" + r.URL.Host + r.URL.Path
	}
	for _, c := range config.Block.Prefix {
		if strings.HasPrefix(fullURL, c) {
			return true
		}
	}
	for _, c := range config.Block.FullURL {
		if c == fullURL {
			return true
		}
	}
	return false
}

type Config struct {
	Block Block
}

type Block struct {
	Prefix  []string `json:"prefix" yaml:"prefix"`
	Suffix  []string `json:"suffix" yaml:"suffix"`
	FullURL []string `json:"full_url" yaml:"fullURL"`
	Hosts   []string `json:"hosts" yaml:"hosts"`
}
